package com.acme.bankapp.service.command;

import com.acme.bankapp.exception.command.CommandException;

import java.util.HashMap;

/**
 * Repository for several commands. {@link Command}
 * @author Gregory Sobko
 */
public class CommandRepository {
    private HashMap<String,Command> commands;

    public CommandRepository() {
        commands = new HashMap<>();
    }

    /**
     * Registers command in repository. It can be later accessed via {@link #getCommand(String)} method<br/>
     * Or Command can be executed directly via {@link #parseAndExecuteCommand(String)}, string received from client
     * @param command
     */
    public void registerCommand(Command command){
        commands.put(command.getCommandPrefix(),command);
    }

    public Command getCommand(String prefix){
        return commands.get(prefix);
    }

    /**
     * Parses and executes command (if found). String will be split in [prefix] [command arguments]<br/>
     * Repository will look if command is registred, and if true,
     * it will execute command.executeCommand([command arguments])
     * @param commandLine command line with format: [prefix] [command arguments]
     * @return status string
     */
    public String parseAndExecuteCommand(String commandLine){
        String[] splittedLine = commandLine.split("\\s",2);
        String prefix = splittedLine[0];
        String commandString = "";
        if(splittedLine.length==2){
            commandString = splittedLine[1];
        }
        System.out.println("Executing command " + prefix +" "+ commandLine+ "!" );
        Command command = commands.get(prefix);
        if(command==null){
            return "Command not found!";
        }else {

            try {
                return command.executeCommand(commandString);
            } catch (CommandException e) {
                return e.getMessage();
            }
        }
    }


}
